<?php


namespace yy\auth;


use think\Model;
use yy\exception\Error;

class Common extends Model
{
    protected $callBack = 'appendFields';
    /**
     * 列表
     * @param $param 分页参数
     * @param bool $where 条件
     * @param bool $order 排序
     * @param bool $fun 对列表数据处理
     * @return array 带分页数组
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($param, $where = false , $order = false  , $fun = false )
    {
        // p($where);
        $curr  = $param[ 'curr' ] ?? 1;
        $row   = $param[ 'row' ] ?? 20;
        $table = $this -> db();
        if ( $where ) {
            $table -> where( $where );
        }
        if ( !empty( $param[ 'name' ] ) ) {
            $table -> where( 'name', 'like', '%' . $param[ 'name' ] . '%' );
        }
        if ($order == false){
            $order = 'id desc';
        }
        // halt($table->buildSql());
        $tableCount = clone $table;
        $list       = $table -> page( $curr, $row )
            -> order( $order );
        if ($fun !== false){
            if ($fun === true) {
                $fun = [$this, $this->callBack];
            }
            $list = $list->select()
                ->each(function ($rt) use ($fun){
                    call_user_func($fun , $rt);
                });

        } else {
            $list = $list->select();
        }
        $count = $tableCount -> count();
        // 总页数
        $pages = (int)ceil( $count / $row ) ?: 1;
        return compact( 'list', 'curr', 'row', 'pages', 'count' );
    }


    /**
     * 详情
     * @param $param 查询id
     * @param bool $fun 数据处理函数
     * @return array|Model|null
     * @throws Error
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDetail( $param , $fun = false )
    {
        if ( empty( $param[ 'id' ] ) ) throw new Error( 400 );
        $result = static ::find( $param[ 'id' ] );
        if ($fun !== false) {
            if ($fun === true) {
                $fun = [$this, $this->callBack];
            }
            call_user_func($fun, $result);
        }
        return $result;
    }


    /**
     * 保存
     */
    public function saveData( $param )
    {

        $param = $param -> toArray();
        unset( $param[ 'create_time' ] );
        unset( $param[ 'update_time' ] );
        if ( empty( $param[ 'id' ] ) ) {
            $result = static ::create( $param );

        } else {
            $result = static ::update( $param );
        }
        return $result;
    }


    /**
     * 删除
     */
    public function deleteRecord( $param )
    {
        if ( empty( $param[ 'id' ] ) ) throw new Error( 201 );

        return static ::destroy( $param[ 'id' ] );

    }

}